<!-- 自动约课设置 -->
<template>
	<view class="auto-appoint-page page-background">
		<view class="item-box top-area">
			<view class="row-item flex-box">
				<view class="label">
					自动约课
				</view>
				<view class="right-switch">
					<uni-switch size="25" inactive-color="#CCCCCC" active-color="#09B501" @change="switchChange" :beforeChange="!switchCanChange?switchBeforeChange:null" :disabled="switchDisabled" v-model="autoFlag"></uni-switch>
					<!-- <uni-switch size="25" inactive-color="#CCCCCC" active-color="#09B501" @change="switchChange" :disabled="switchDisabled" v-model="autoFlag"></uni-switch> -->
				</view>
			</view>
			<view class="tips">
				开启状态时，系统将提前7天按照约课设置自动为您约课，7天内的课程仍然需要您手动约课。预约成功后会有短信通知，您可以通过约课记录查看约课信息或取消预约。
			</view>
		</view>
		<view class="item-box bottom-area">
			<view class="label">
				约课设置
			</view>
			<view v-if="edit" class="course-slot-view">
				<view class="top-row flex-box">
					<van-checkbox :value="allChecked" @change="allCheckboxChange">全选</van-checkbox>
					<view @click="saveTemplate" class="save-btn">
						保存
					</view>
				</view>
				<view class="day-list">
					<view class="day-item" v-for="(item,index) in slotsArr" :key="index">
						<!-- <view class="slot-row day-label">
							<van-icon></van-icon>
							<text>{{filterWeek(item.name)}}</text>
						</view> -->
						<view class="day-all">
							<van-checkbox :value="weekCheckedArr[index].all" @change="weekCheckboxChange($event,index)">{{filterWeek(item.name)}}</van-checkbox>
						</view>
						<van-checkbox-group :value="weekCheckedArr[index].slotCheckedArr" @change="checkboxGroupChange($event,index)">
							<view v-for="(obj,idx) in item.slotArr" :key="idx" class="slot-row">
								<van-checkbox :name="obj.name">{{obj.value}}</van-checkbox>
							</view>
						</van-checkbox-group>
					</view>
				</view>
			</view>
			<view v-else class="course-slot-view">
				<view class="top-row flex-box">
					<view class="slots-tips">
						以下为已选时间段
					</view>
					<view @click="startEdit" class="save-btn">
						编辑
					</view>
				</view>
				<view class="day-list">
					<view class="day-item-show" v-for="(item,index) in showSlotsArr" :key="index">
						<!-- <view class="slot-row day-label">
							<van-icon></van-icon>
							<text>{{filterWeek(item.name)}}</text>
						</view> -->
						<view class="day-show">
							{{filterWeek(item.name)}}
						</view>
						<view class="slot-row">
							{{item.slotsString}}
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 弹出框 -->
		<van-dialog id="van-dialog" confirm-button-color="#2E87FF" cancel-button-color="#2E87FF" />
	</view>
</template>

<script>
	import {
		mapState,
		mapGetters,
		mapMutations
	} from 'vuex'
	import {
		dateUtils,
		rili
	} from '@/common/js/util.js'
	import Dialog from '@/wxcomponents/vant/dist/dialog/dialog'
	let statusShowText = ''
	export default {
		data() {
			return {
				autoFlag: true,
				switchDisabled: false,
				classId: '',
				clubId: '',
				classEnterId: '',
				userId: '',
				allChecked: false,
				slotsArr: [],
				weekCheckedArr:[],
				slotsCheckedArr:[],
				classDetailInfo:{},
				edit: false,
				showSlotsArr: [], // 已经保存的自动约课时间段数组
				switchCanChange: true,
				statusShowText: ''
			};
		},
		onLoad(option) {
			this.classId = option.classId || ''
			// this.clubId = option.clubId || ''
			this.classEnterId = option.classEnterId || ''
			// this.userId = option.userId || ''
			this.init()
			// this.getClassDetail()
		},
		computed:{
			...mapState(['accessToken','userInfo']),
		},
		methods: {
			gotoback() {
				//返回上一页
				uni.navigateBack();
			},
			async init() {
				const param = {
					'ACCESS-TOKEN': this.accessToken,
					pageSize: 9999,
					pageNo: 1,
					classId: this.classId
				}
				const res = await this.$api.queryClassEnterList(param)
				if (res && res.code == 200) {
					let arr = res.data.list.filter((item)=>{return item.id == this.classEnterId})
					this.classEnterDetail = arr[0]
					this.userId = arr[0].userId
					this.clubId = arr[0].clubId
					if(this.classEnterDetail.orderStatus==3||this.classEnterDetail.orderStatus==6||this.classEnterDetail.classState==2){
						this.autoFlag = false
						this.switchCanChange = false
						this.statusShowText = this.classEnterDetail.orderStatus==6 ? this.classEnterDetail.orderStatusName : this.classEnterDetail.classStateStr
						statusShowText = this.classEnterDetail.orderStatus==6 ? this.classEnterDetail.orderStatusName : this.classEnterDetail.classStateStr
						// 自动关闭自动约课设置
						if(this.classEnterDetail.isAutoTimetable == '1'){
							this.updateAutoTimeTable(true)
						}
					}else{
						this.autoFlag = arr[0].isAutoTimetable == '1' ? true : false
					}
					this.getClassDetail()
				}
			},
			switchChange(e){
				this.switchDisabled = true
				let timer = setTimeout(()=>{
					this.switchDisabled = false
					clearTimeout(timer)
				},3000)
				if(this.switchCanChange){
					this.updateAutoTimeTable()
				}else{
					this.autoFlag = false
				}
				// this.updateAutoTimeTable()
			},
			switchBeforeChange(e){
				let tipsContent = `当前课程${statusShowText}，不能开启约课设置哦！`
				Dialog.alert({
					message: tipsContent,
					confirmButtonText: '知道啦',
					width: '325px',
					messageAlign: 'left',
					customStyle: 'border-radius:7.5px;',
					className: 'my-dialog-confirm'
				})
			},
			async getClassDetail(){
				const res = await this.$api.getClassDetailById({"ACCESS-TOKEN": this.accessToken},this.classId)
				if(res&&res.code==200){
					this.classDetailInfo = res.data
					this.getResTemplateList()
				}
			},
			async getResTemplateList(){
				let param = {
					"ACCESS-TOKEN": this.accessToken,
					classId: this.classId,
					clubId: this.clubId,
					classEnterId: this.classEnterId,
					userId: this.userId
				}
				const res = await this.$api.queryResTemplateList(param)
				if(res&&res.code==200){
					this.makeSlotsArr(this.classDetailInfo.spClassSlots,res.data)
					this.makeShowSetting(res.data)
				}
			},
			async saveResTemplate(data){
				let param = {
					"ACCESS-TOKEN": this.accessToken,
					...data
				}
				const res = await this.$api.saveResTemplate(param)
				if(res&&res.code==200){
					this.getResTemplateList()
					this.edit = false
				}
				uni.showToast({
					title: res.message,
					icon: 'none'
				})
			},
			async updateAutoTimeTable(auto=false){
				let param = {
					"ACCESS-TOKEN": this.accessToken,
					classEnterId: this.classEnterId,
					isAutoTimetable: this.autoFlag?'1':'0'
				}
				const res = await this.$api.updateAutoTimeTable(param)
				if(res&&res.code==200){
					this.autoFlag = res.data.isAutoTimetable == '1' ? true : false
				}
				
				if(auto){
					let tipsContent = `当前课程${this.statusShowText}，系统已关闭约课设置`
					Dialog.alert({
						message: tipsContent,
						confirmButtonText: '知道啦',
						width: '325px',
						messageAlign: 'left',
						customStyle: 'border-radius:7.5px;',
						className: 'my-dialog-confirm'
					})
				}else{
					uni.showToast({
						title: res.message,
						icon: 'none',
						duration: 2500
					})
				}
			},
			makeShowSetting(arr){
				let [weekArr,newArr] = [['1','2','3','4','5','6','7'],[]]
				weekArr.forEach((item,index)=>{
					let weekObj = {
						slotArr: []
					}
					arr.forEach((obj,idx)=>{
						if(obj.week.includes(item)){
							let slotText = obj.startTime.substr(0,5)+'-'+obj.endTime.substr(0,5)
							if(!weekObj.name){
								weekObj.name = item
							}
							weekObj.slotArr.push(slotText)
						}
					})
					if(weekObj.slotArr.length>0){
						weekObj.slotsString = weekObj.slotArr.join('、')
						newArr.push(weekObj)
					}
				})
				this.showSlotsArr = newArr
			},
			allCheckboxChange(e){
				this.allChecked = e.detail
				this.weekCheckedArr.forEach((item,index)=>{
					this.weekCheckboxChange({detail:e.detail},index)
				})
			},
			weekCheckboxChange(e,v){
				this.weekCheckedArr[v].all = e.detail
				if(e.detail){
					let arr = []
					this.slotsArr[v].slotArr.forEach((item,index)=>{
						arr.push(item.name)
					})
					this.weekCheckedArr[v].slotCheckedArr = arr
				}else{
					this.weekCheckedArr[v].slotCheckedArr = []
				}
				
				// 是否全选
				let arr = this.weekCheckedArr.filter((item)=>{return item.all})
				if(arr.length==this.weekCheckedArr.length){
					this.allChecked = true
				}else{
					this.allChecked = false
				}
			},
			checkboxGroupChange(e,v){
				this.weekCheckedArr[v].slotCheckedArr = e.detail
				// this.$set(this.checkedArr,v,{slotArr:e.detail})
				// 当天是否全选
				if(e.detail.length == this.slotsArr[v].slotArr.length){
					this.weekCheckedArr[v].all = true
				}else{
					this.weekCheckedArr[v].all = false
				}
				
				// 是否全选
				let arr = this.weekCheckedArr.filter((item)=>{return item.all})
				if(arr.length==this.weekCheckedArr.length){
					this.allChecked = true
				}else{
					this.allChecked = false
				}
			},
			makeSlotsArr(arr=[],checkedArr=[]){
				if(arr.length>0){
					let [weekArr,newArr,newCheckedArr] = [['1','2','3','4','5','6','7'],[],[]]
					weekArr.forEach((item,index)=>{
						let weekObj = {
							slotArr: []
						}
						let weekCheckedObj = {
							all: false,
							slotCheckedArr: []
						}
						arr.forEach((obj,idx)=>{
							if(obj.week.includes(item)){
								let slotText = obj.startTime.substr(0,5)+'-'+obj.endTime.substr(0,5)
								if(!weekObj.name){
									weekObj.name = item
								}
								weekObj.slotArr.push({
									name: String(idx),
									value: slotText,
									classSlotId: obj.id,
									week: item,
									startTime: obj.startTime,
									endTime: obj.endTime
								})
								checkedArr.forEach((o,i)=>{
									if(o.classSlotId==obj.id&&o.week==item){
										weekCheckedObj.slotCheckedArr.push(String(idx))
									}
								})
							}
						})
						if(weekObj.slotArr.length>0){
							if(weekCheckedObj.slotCheckedArr.length == weekObj.slotArr.length){
								weekCheckedObj.all = true
							}
							newArr.push(weekObj)
							newCheckedArr.push(weekCheckedObj)
						}
					})
					this.slotsArr = newArr
					this.weekCheckedArr = newCheckedArr
					
					// 是否全选
					let allArr = this.weekCheckedArr.filter((item)=>{return item.all})
					if(allArr.length==this.weekCheckedArr.length){
						this.allChecked = true
					}else{
						this.allChecked = false
					}
				}
			},
			filterWeek(f){
				switch(f){
					case '1':
						return '周一';
					case '2':
						return '周二';
					case '3':
						return '周三';
					case '4':
						return '周四';
					case '5':
						return '周五';
					case '6':
						return '周六';
					case '7':
						return '周日';
					default: 
						return '周日'
				}
			},
			saveTemplate(){
				let arr = []
				this.weekCheckedArr.forEach((item,index)=>{
					if(item.slotCheckedArr.length>0){
						let slotArr = this.slotsArr[index].slotArr
						slotArr.forEach((obj,idx)=>{
							if(item.slotCheckedArr.includes(obj.name)){
								arr.push({
									classSlotId: obj.classSlotId,
									endTime: obj.endTime,
									startTime: obj.startTime,
									week: obj.week
								})
							}
						})
					}
				})
				let param = {
					classId: this.classId,
					clubId: this.clubId,
					classEnterId: this.classEnterId,
					userId: this.userId,
					spClassTimetableTemplateParamList: arr
				}
				this.saveResTemplate(param)
			},
			startEdit(){
				if(this.switchCanChange){
					this.edit = true
				}else{
					let tipsContent = `当前课程${this.statusShowText}，不能开启约课设置哦！`
					Dialog.alert({
						message: tipsContent,
						confirmButtonText: '知道啦',
						width: '325px',
						messageAlign: 'left',
						customStyle: 'border-radius:7.5px;',
						className: 'my-dialog-confirm'
					})
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.auto-appoint-page {
		min-height: 100vh;
		overflow: hidden;
		padding-bottom: 30rpx;
		.top-area{
			padding: 20rpx;
			.row-item{
				align-items: center;
				.label{
					font-size: 34rpx;
				}
			}
			.tips{
				font-size: 24rpx;
				line-height: 48rpx;
				margin-top: 20rpx;
				color: #999999;
			}
		}
		.bottom-area{
			.label{
				font-size: 34rpx;
				line-height: 34rpx;
				padding: 30rpx 20rpx;
			}
			.course-slot-view{
				.top-row{
					border-bottom: 1rpx solid #E9E9E9;
					// border-top: none!important;
					padding: 0 20rpx 20rpx;
					.slots-tips{
						color: #999999;
						font-size: 28rpx;
					}
					.save-btn{
						width: 125rpx;
						height: 43rpx;
						background-color: #6BA9FE;
						border-radius: 5rpx;
						font-size: 24rpx;
						color: #FFF;
						text-align: center;
						line-height: 43rpx;
					}
				}
				.day-list{
					padding: 0 20rpx;
					.day-item{
						padding: 40rpx 0 20rpx;
						border-bottom: 1rpx solid #E9E9E9;
						.day-all{
							padding-bottom: 20rpx;
						}
						.day-show{
							font-size: 36rpx;
						}
						.slot-row{
							padding: 20rpx 0;
						}
					}
					.day-item-show{
						padding: 30rpx 0 20rpx;
						border-bottom: 1rpx solid #E9E9E9;
						.day-show{
							font-size: 36rpx;
						}
						.slot-row{
							padding: 10rpx 0;
						}
					}
				}
			}
		}
	}
</style>
<style lang="scss">
	.day-all{
		.van-checkbox__label{
			font-size: 36rpx!important;
			color: #333!important;
		}
	}
</style>
